package com.abe.libquick.main.audio;

import android.content.Context;
import android.net.Uri;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.abe.libcore.utils.CommonUtils;
import com.abe.libquick.R;
import com.abe.libquick.base.BaseActivity;
import com.abe.libquick.main.audio.record.AudioPlayManager;
import com.abe.libquick.main.audio.record.AudioRecordManager;
import com.abe.libquick.main.audio.record.IAudioPlayListener;
import com.abe.libquick.main.audio.record.IAudioRecordListener;
import com.abe.libquick.main.audio.widget.RecordAudioButton;
import com.abe.libquick.main.audio.widget.RecordVoicePopWindow;
import com.abe.libquick.main.audio.widget.VideoAdapter;
import com.abe.libquick.utils.ConstantMBLib;
import com.abe.libquick.utils.quick.EmptyUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AudioMainActivity extends BaseActivity {

    private static final int MAX_VOICE_TIME = 20;//声音最大时间
    private static final String AUDIO_DIR_NAME = "audio_cache";
    LinearLayout mRoot;
    RecyclerView mRvMsg;//消息列表
    RecordAudioButton mBtnVoice;//底部录制按钮
    private List<File> list;
    private Context mContext;
    private File mAudioDir;
    private VideoAdapter mAdapter;//适配器
    private RecordVoicePopWindow mRecordVoicePopWindow;//提示

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_audio_main;
    }

    @Override
    protected void initContent() {
        mContext = this;
        mAudioDir = new File(ConstantMBLib.CS_CORE, AUDIO_DIR_NAME);
        if (!mAudioDir.exists()) {//判断文件夹是否存在，不存在则创建
            boolean success = mAudioDir.mkdirs();
            System.out.println(success);
        }
        list = new ArrayList<>();
        mAdapter = new VideoAdapter(list);
        initView();//初始化布局
        initAudioManager();
        loadAudioCacheData();
    }

    private void initView() {
        mRoot = findViewById(R.id.root);
        mRvMsg = findViewById(R.id.rvMsg);
        mBtnVoice = findViewById(R.id.btnVoice);
        mBtnVoice.setOnVoiceButtonCallBack(new RecordAudioButton.OnVoiceButtonCallBack() {
            @Override
            public void onStartRecord() {
                AudioRecordManager.getInstance(mContext).startRecord();
            }

            @Override
            public void onStopRecord() {
                AudioRecordManager.getInstance(mContext).stopRecord();
            }

            @Override
            public void onWillCancelRecord() {
                AudioRecordManager.getInstance(mContext).willCancelRecord();
            }

            @Override
            public void onContinueRecord() {
                AudioRecordManager.getInstance(mContext).continueRecord();
            }
        });
        mRvMsg.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (R.id.iv_voice == view.getId()) {
                File item = list.get(position);
                Uri audioUri = Uri.fromFile(item);
                CommonUtils.INSTANCE.log("P_startPlayRecord:" + audioUri.toString());
                AudioPlayManager.getInstance().startPlay(mContext, audioUri, new IAudioPlayListener() {
                    @Override
                    public void onStart(Uri var1) {
                        mAdapter.startPlayAnim(position);
                    }

                    @Override
                    public void onStop(Uri var1) {
                        mAdapter.stopPlayAnim();
                    }

                    @Override
                    public void onComplete(Uri var1) {
                        mAdapter.stopPlayAnim();
                    }
                });
            }
        });
        mRvMsg.setAdapter(mAdapter);
    }

    /**
     * 初始化音频播放管理对象
     */
    private void initAudioManager() {
        AudioRecordManager.getInstance(mContext).setAudioSavePath(mAudioDir.getAbsolutePath());
        AudioRecordManager.getInstance(mContext).setMaxVoiceDuration(MAX_VOICE_TIME);
        AudioRecordManager.getInstance(mContext).setAudioRecordListener(new IAudioRecordListener() {
            @Override
            public void initTipView() {
                if (mRecordVoicePopWindow == null) {
                    mRecordVoicePopWindow = new RecordVoicePopWindow(mContext);
                }
                mRecordVoicePopWindow.showAsDropDown(mRoot);
            }

            @Override
            public void setTimeoutTipView(int counter) {
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.showTimeOutTipView(counter);
                }
            }

            @Override
            public void setRecordingTipView() {
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.showRecordingTipView();
                }
            }

            @Override
            public void setAudioShortTipView() {
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.showRecordTooShortTipView();
                }
            }

            @Override
            public void setCancelTipView() {
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.showCancelTipView();
                }
            }

            @Override
            public void destroyTipView() {
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.dismiss();
                }
            }

            @Override
            public void onStartRecord() {

            }

            @Override
            public void onFinish(Uri audioPath, int duration) {
                if (EmptyUtils.isEmpty(audioPath) || EmptyUtils.isEmpty(audioPath.getPath()))
                    return;
                File file = new File(audioPath.getPath());
                if (file.exists()) {
                    toast(R.string.community_chat_list_rec_voice_success);
                    loadAudioCacheData();
                }
            }

            @Override
            public void onAudioDBChanged(int db) {
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.updateCurrentVolume(db);
                }
            }
        });
    }

    private void loadAudioCacheData() {
        if (mAudioDir.exists()) {
            List<File> mListData = new ArrayList<>();
            File[] files = mAudioDir.listFiles();
            files = files == null ? new File[0] : files;
            for (File file : files) {
                if (file.getAbsolutePath().endsWith("m4a")) {
                    mListData.add(file);
                }
            }
            this.list.clear();
            this.list.addAll(mListData);
            mAdapter.notifyDataSetChanged();
        }
    }
}